<template>
	<div v-cloak>

		<!--工具条-->
		<div name="searchColums" id="searchColums">
			<el-form :inline="true" :model="filters" size="small" ref="filters" class="searchForm">
				<el-form-item class="el-form-item" label="标题">
					<el-input v-model="filters.title" name="title" auto-complete="off" placeholder="请输入"></el-input>
				</el-form-item>

				<span class="bth_search">
					<el-form-item>
			    		<el-button type="success" icon="el-icon-search" v-on:click="getFeeApply(true)">查询</el-button>
			    	</el-form-item>
			    	<el-form-item>
			    		<el-button icon="el-icon-refresh" @click="resetSearchForm('filters')">重置</el-button>
			    	</el-form-item>
				</span>
			</el-form>
		</div>
		<!--toolbar-->
		<el-row id="toolbar">
			<el-col :span="24">
				<div class="grid-content bg-purple-light">
					<el-button type="primary" size="mini"icon="el-icon-edit" @click="handleAdd">新增</el-button>
				</el-button>
				<el-button  type="success" size="mini" icon="el-icon-check"  @click="processStart">发起流程</el-button>
          		<el-button  type="success" size="mini" icon="el-icon-check"  @click="processMap">查看流程图</el-button>
				</div>
			</el-col>
		</el-row>

		<!--列表-->
		<el-table :data="feeApplyDatas" id="datagrid" empty-text=" " height="410" border stripe size="mini" :header-row-class-name="headStyle" highlight-current-row v-loading="listLoading" :row-class-name="tableRowClassName" @sort-change="handleSortChange" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="45"></el-table-column>
			<el-table-column prop="index" :formatter="index_formatter" label="序号" width="60"></el-table-column>
			<el-table-column prop="title" label="标题"  show-overflow-tooltip></el-table-column>
			<el-table-column prop="feeNum" label="费用金额" width="90" show-overflow-tooltip></el-table-column>
			<el-table-column prop="applyUserName" label="申请人" width="90" show-overflow-tooltip></el-table-column>
			<el-table-column prop="applyTime" label="申请时间" show-overflow-tooltip></el-table-column>
			<el-table-column prop="feeType" label="费用类型" width="100" show-overflow-tooltip></el-table-column>
			 <el-table-column prop="processId" v-if="false"></el-table-column>
			<el-table-column prop="statusName" label="流程状态" width="80" show-overflow-tooltip></el-table-column>
			<el-table-column label="操作" width="160" fixed="right">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar" id="pageDiv">
			<el-pagination small background @current-change="handleCurrentChange" @size-change="handleSizeChange" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" layout="total,sizes, prev, pager, next" style="float:right;"></el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" @close="resetForm('editForm')">
			<el-form :model="editForm" label-width="120px" :rules="addFormRules" ref="editForm" size="mini">
				<el-input v-model="editForm.applyUser" type="hidden" style="display: none!important;"></el-input>
				<el-form-item label="申请人" prop="applyUserName">
					<el-input v-model="editForm.applyUserName" disabled></el-input>
				</el-form-item>
				<el-form-item label="标题" prop="title">
					<el-input v-model="editForm.title" auto-complete="off" placeholder="请输入"></el-input>
				</el-form-item>
				<el-form-item label="费用金额" prop="feeNum">
					<el-input v-model.number="editForm.feeNum" auto-complete="off" placeholder="请输入">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="费用类型" prop="feeType">
					<el-input v-model="editForm.feeType" auto-complete="off" placeholder="请输入"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="resetForm('addForm')">
			<el-form :model="addForm" label-width="120px" :rules="addFormRules" ref="addForm" size="mini">
				<el-input v-model="addForm.applyUser" type="hidden" style="display: none!important;"></el-input>
				<el-form-item label="申请人" prop="applyUserName">
					<el-input v-model="addForm.applyUserName" disabled></el-input>
				</el-form-item>
				<el-form-item label="标题" prop="title">
					<el-input v-model="addForm.title" auto-complete="off" placeholder="请输入"></el-input>
				</el-form-item>
				<el-form-item label="费用金额" prop="feeNum">
					<el-input v-model.number="addForm.feeNum" auto-complete="off" placeholder="请输入">
						<template slot="append">元</template>
					</el-input>
				</el-form-item>
				<el-form-item label="费用类型" prop="feeType">
					<el-input v-model="addForm.feeType" auto-complete="off" placeholder="请输入"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>

		<el-dialog title="审批人选择" :visible.sync="dialogDeptVisible">
			<userTree ref="building_tree" deptProperty="0,1" @treeNode-click="treeNodeClick"></userTree>
		</el-dialog>
 		<!--图片查看界面-->
    	<el-dialog title="流程图" :visible.sync="imgFormVisibleLct" :close-on-click-modal="false">
      		<el-row>
        		<img :src="'/acti/process/getProcImage?processInstanceId='+processInstanceId" class="image"/>
      		</el-row>
    	</el-dialog>
	</div>
</template>
<script>
	import { getToken, setToken, removeToken } from '@/util/auth'
	import request from '@/router/axios'
	import {mapGetters,mapState} from "vuex";
	import userTree from '../feeApplyRecord/userTree.vue';
	export default {
		name: 'table_fee_apply',
		components: {
		    userTree
		},
		data() {
			return {
				treeDeptData: [],
				filters: {
					title: ''
				},
				url: {
					list: '/admin/feeApplyRecord/page',
					del: '/admin/feeApplyRecord/doDel',
					save: '/admin/feeApplyRecord/',
					edit: '/admin/feeApplyRecord/doUpdate'
				},
				feeApplyDatas: [],
				fileList: [],
				processInstanceId:"",
				total: 0,
				page: 1,
				pageSize: 10,
				sort: {
					sort: 'sort',
					order: 'asc'
				},
				listLoading: false,
				sels: [], //列表选中列

				editFormVisible: false, //编辑界面是否显示
				importFormVisible: false,
				dialogDeptVisible: false,
				imgFormVisibleLct:false,
				editLoading: false,
				dialogStatus: '',
				deptOptions: [],
				editFormRules: {},

				addFormVisible: false, //新增界面是否显示
				addLoading: false,
				addFormRules: {
					title: [{
						required: true,
						message: '请输入费用标题'
					}]
				},
				//新增界面数据
				addForm: {
					title: '',
					applyUser: '',
					applyUserName: '',
					feeNum: '',
					feeType: ''
				},
				//编辑界面数据
				editForm: {
					title: '',
					applyUser: '',
					applyUserName: '',
					feeNum: '',
					feeType: ''
				},
				formFile: {},

				defaultProps: {
					children: 'children',
					label: 'name'
				},
				//数据字典
				propertyRightOptions: [],
				restaurantsDept: []
			}
		},

		methods: {
			getNodeData(data) {
				this.dialogDeptVisible = false
				this.addForm.deptId = data.id
				this.addForm.deptName = data.name
				this.editForm.deptId = data.id
				this.editForm.deptName = data.name
			},
			handleDept() {
				fetchDeptTree().then(response => {
					this.treeDeptData = response.data
					this.dialogDeptVisible = true
				})
			},
			handleSortChange(sort) {
				this.sort = {
					sort: sort.prop,
					order: sort.order == 'ascending' ? 'asc' : 'desc'
				};
				this.getFeeApply();
			},
			tableRowClassName(row, index) {
				//把每一行的索引放进row
				row.index = row.rowIndex
			},
			headStyle({
				row,
				rowIndex
			}) {
				return "table_head_style";
			},
			index_formatter: function(row, column, cellValue, index) {
				//放回索引值
				return(this.pageSize * (this.page - 1) + 1 + index);
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getFeeApply();
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.page = 1;
				this.getFeeApply();
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			resetSearchForm(forName) {
				this.filters = {
					title: ''
				}
			},

			//获取用户列表
			getFeeApply(flag) {
				if(flag){
					this.page = 1;
				}
				let para = {
					params: {
						page: this.page,
						limit: this.pageSize,
						//排序
						orderByField: this.sort.sort,
						isAsc: this.sort.order,
						title: this.filters.title
					}
				};
				this.listLoading = true;
				request.get(this.url.list, para).then((res) => {
					this.total = res.data.total;
					var datas = res.data.records;
					this.feeApplyDatas = datas;
					this.listLoading = false;
				});
			},
			//删除
			handleDel: function(index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					let para = {
						id: row.id
					};
					request.get(this.url.del, {
						params: para
					}).then((res) => {
						this.listLoading = false;
						this.$message({
							message: '删除成功',
							type: 'success',
							duration: 1500
						});
						this.getFeeApply();
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function(index, row) {
				this.dialogStatus = 'update'
				this.editFormVisible = true;
				var item = {};
				this.editForm = Object.assign({}, row);
				for(var i = 0; i < this.restaurantsDept.length; i++) {
					if(this.restaurantsDept[i].deptId == row.deptId) {
						item.name = this.restaurantsDept[i].name;
						item.deptId = this.restaurantsDept[i].deptId;
						break;
					}
				}

				this.formFile = {};
				this.handleSelect(item)
			},
			//显示新增界面
			handleAdd: function() {
				this.dialogStatus = 'create'
				this.addFormVisible = true;
				this.addForm = {
					applyUserName:this.userInfo.realname,
					applyUser:this.userInfo.userId
				};
				this.formFile = {};
			},
			//编辑
			editSubmit: function() {
				this.$refs.editForm.validate((valid) => {
					if(valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							let para = Object.assign({}, this.editForm);
							request.post(this.url.edit, para).then((res) => {
								this.editLoading = false;
								this.$message({
									message: '提交成功',
									type: 'success',
									duration: 1500
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getFeeApply();
							});
						});
					} // if(valid)结束
				});
			},
			//新增
			addSubmit: function() {
				this.$refs.addForm.validate((valid) => {
					if(valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							let communityBuilding = Object.assign({}, this.addForm);

							communityBuilding.createDate = !communityBuilding.createDate ? '' : utilFormatDate(new Date(communityBuilding.createDate), 'yyyy-MM-dd');

							request.post(this.url.save, communityBuilding).then((res) => {
								this.addLoading = false;
								this.$message({
									message: '提交成功',
									type: 'success',
									duration: 1500
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getFeeApply();
							});
						});
					} // if(valid)结束
				});
			},
			selsChange: function(sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function() {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					let para = {
						ids: ids
					};
					request.get(this.url.batchDel, {
						params: para
					}).then((res) => {
						this.listLoading = false;
						this.$message({
							message: '删除成功',
							type: 'success',
							duration: 1500
						});
						this.getFeeApply();
					});
				}).catch(() => {});
			},
			//初始化数据字典
			initDictsData: function() {
				//              request.get("admin/dict/type/log_type").then((res) => {
				//                  if(res.ok){
				//                      this.propertyRightOptions = res.body;
				//					}
				//              });
				//初始化部门列表
				request.get("admin/community/deptList").then((res) => {
					if(res.status === 200) {
						this.restaurantsDept = res.data;
					}
				});
			},

			querySearch(queryString, cb) {
				var restaurants = this.restaurantsDept;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// 调用 callback 返回建议列表的数据
				cb(results);
			},
			createFilter(queryString) {
				return(restaurantsDept) => {
					return(restaurantsDept.name.toString().indexOf(queryString) === 0);
				};
			},

			handleSelect(item) {
				if(this.addFormVisible) {
					this.addForm.deptId = item.deptId;
					this.addForm.deptName = item.name;
				} else {
					this.editForm.deptId = item.deptId;
					this.editForm.deptName = item.name;
				}

			},
			handleIconClick(ev) {
				console.log(ev);
			},
			initDictByCode: function(code, _this, dictOptionsName) {
				if(!code || !_this[dictOptionsName] || _this[dictOptionsName].length > 0)
					return;
				request.get(this.url.queryDict, {
					params: {
						typeGroupName: code
					}
				}).then((res) => {
					var data = res.data;
					if(data.success) {
						_this[dictOptionsName] = data.obj;
						_this[dictOptionsName].splice(0, 1); //去掉请选择
					}
				});
			},
			processMap:function(){
				this.processInstanceId=this.sels.map(item => item.processId).toString();
    			this.imgFormVisibleLct = true;
			},
			processStart:function(){
				var id = this.sels.map(item => item.id).toString();
				if(id.length==0||id.split(",").length>1){
      				this.$message({message: '请选择发起流程记录',type: 'info',duration: 1500});
      				return;
      			}
				this.dialogDeptVisible = true;
			},
			treeNodeClick(data, node) {
				if(!(data.type=="user")){
					return;
				}
				this.$confirm('确认发送流程吗?', '提示', {type: 'warning'}).then(()=>{
					
      			var id = this.sels.map(item => item.id).toString();
      			var description = this.sels.map(item => item.title).toString();
			    let para = {fromId:id,
			      	fromUser:this.userInfo.realname,
			      	fromTable:"fee_apply_record",
			      	title:"费用申报流程-"+description,
			      	processKey:"process_fee_apply",
			      	opId:data.id
			    };
      			let strs = Object.assign({}, para);
      			request.post('/acti/process/addScspProcess', strs).then(res => {
              		if(res.data.code=="200"){
              			this.editForm={
              				processId:res.data.data,
              				status:1,
              				id:id
              			}
              			let para1 = Object.assign({}, this.editForm)
			            request.put("/admin/feeApplyRecord/", para1).then(res => {
			              this.$message({
			                message: '启动成功',
			                type: 'success',
			                duration: 1500
			              });
			              this.dialogDeptVisible = false;
			              this.getFeeApply();
			            });
              		}
              	})
				});
      			
    		}
		},
		mounted() {

			this.initDictsData();
			this.getFeeApply();
		},
		computed: {
      		...mapState({
      			userInfo: state => state.user.userInfo
      		})
    	},
    	created() {
    	}
	};

</script>